#include "stm32f10x.h"                  // Device header
#include "Delay.h"

#define I2C_SCL			GPIO_Pin_0
#define I2C_SDA			GPIO_Pin_1

void My_I2C_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
	GPIO_InitStructure.GPIO_Pin = I2C_SCL | I2C_SDA;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_SetBits(GPIOA, I2C_SCL | I2C_SDA);
}

void My_I2C_W_SCL(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA, I2C_SCL, (BitAction)BitValue);
	Delay_us(10);
}

void My_I2C_W_SDA(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA, I2C_SDA, (BitAction)BitValue);
	Delay_us(10);
}

uint8_t My_I2C_R_SDA(void)
{
	uint8_t BitValue;
	BitValue = GPIO_ReadInputDataBit(GPIOA, I2C_SDA);
	Delay_us(10);
	return BitValue;
}

void My_I2C_Start(void)
{
	My_I2C_W_SDA(1);
	My_I2C_W_SCL(1);
	My_I2C_W_SDA(0);
	My_I2C_W_SCL(0);
}

void My_I2C_Stop(void)
{
	My_I2C_W_SDA(0);
	My_I2C_W_SCL(1);
	My_I2C_W_SDA(1);
}

void My_I2C_SendByte(uint8_t Byte)
{
	uint8_t i;
	for(i = 0; i < 8; i ++)
	{
		My_I2C_W_SDA(Byte & (0x80 >> i));
		My_I2C_W_SCL(1);
		My_I2C_W_SCL(0);
	}
}

uint8_t My_I2C_ReceiveByte(void)
{
	uint8_t Byte = 0x00;
	uint8_t i;
	for(i = 0; i < 8; i ++)
	{
		My_I2C_W_SCL(1);
		if(My_I2C_R_SDA() == 1)
		{
			Byte |= (0x80 >> i);
		}
		My_I2C_W_SCL(0);
	}
	return Byte;
}

void My_I2C_SendAck(uint8_t AckValue)
{
	My_I2C_W_SDA(AckValue);
	My_I2C_W_SCL(1);
	My_I2C_W_SCL(0);
}

uint8_t My_I2C_ReceiveAck(void)
{
	uint8_t AckValue;
	My_I2C_W_SDA(1);
	My_I2C_W_SCL(1);
	AckValue = My_I2C_R_SDA();
	My_I2C_W_SCL(0);
	return AckValue;
}
